<template>
  <div class="app-container documentation-container">
    <div class="graph_wrapper" id="graph_wrapper">
      <el-carousel 
        trigger="click" 
        :autoplay="false" 
        id="carousel" 
        :class="{ carousel: true, hide: isVisible }" 
        :interval="15000" 
        @change="carouselChange"
        indicator-position="outside" >
        <el-carousel-item v-for="(item, index) in maps" :key="index" class="graph_container">
          <!-- <div class="total">设备总数: {{item.devCount}}</div> -->
          <div class="projectWraper">
            <div class="infoBox">
              <div class="projectInfo">
                <div class="title">项目简介</div>
                <div v-if="item.projectExplain">{{item.projectExplain}}</div>
                <div v-if="!item.projectExplain">项目名称：{{item.projectName}}</div>
                <div v-if="!item.projectExplain">该项目位于: {{ item.provinceName + item.cityName + item.countyName}}</div>
                <!-- <div class="imgWraper">
                  <img :style="{ height: tableHeight * 2 - 110 + 'px',  }" v-if="item.projectPicture" :src="item.projectPicture" alt="">
                  <img :style="{ height: tableHeight * 2 - 110 + 'px',  }" v-else src="../../assets/imgs/prodefault.jpg" alt="">
                </div> -->
              </div>
              <el-table 
              class="deviceTable"
              size="mini"
              :row-class-name="rowClassName"
              :maxHeight="tableHeight"
              @row-dblclick="rowDbClickChange(item, $event)"
              :data="item.devices">
                <el-table-column prop="imei" label="IMEI" width="160" show-overflow-tooltip></el-table-column>
                <el-table-column prop="deviceName" label="设备名称" width="160" show-overflow-tooltip></el-table-column>
                <!-- <el-table-column prop="dataStatus" align="left" label="设备状态" width="80" show-overflow-tooltip></el-table-column> -->
                <!-- <el-table-column prop="rfid" label="自定义编码" width="180" show-overflow-tooltip></el-table-column> -->
                <el-table-column prop="insTime" label="安装时间" width="110" show-overflow-tooltip></el-table-column>
                <el-table-column prop="dataStatus" align="left" label="告警等级" width="80" show-overflow-tooltip></el-table-column>
                <!-- <el-table-column prop="imei" label="标签" width="180" show-overflow-tooltip></el-table-column> -->
                <!-- <el-table-column prop="" align="left" label="地图位置" width="80">
                  <template slot-scope="scope">
                    <i class="el-icon-map-location" @click="navTodevice(item, scope.row)"></i>
                  </template>
                </el-table-column> -->
                <el-table-column prop="" label="设备位置" minWidth="120" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span>{{ item.projectAddrInfo }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="项目名称" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span>{{ item.projectName }}</span>
                  </template>
                </el-table-column>
              </el-table>
              

            </div>
            <div 
              class="mapWrapper" 
              :id="'exampleMap' + index" 
              :style="{ height: mapHeight + 'px', width: '100%', border: '2px solid #141F3B'}"> </div>
            </div>
        </el-carousel-item>
      </el-carousel>

    </div>
  </div>
</template>

<script>
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import { transformFromGCJToWGS, transformFromWGSToGCJ } from '../project/WSCoordinate'

import { loadProjectList, myProjectDetail, movePoint, loadCustomerProjects } from '@/api/myProject'
export default {
  name: 'projectGraph',
  data() {
    return {
      zoomLevel: 4,
      tableHeight: 300,
      mapHeight: 500,
      ak: 'k5LYzWjOinI5GOcHpBgdxieo5ZVPGtLj',
      isVisible: false,
      autoplay: true,
      detail: { projectName: '北京'},
      mapExample: null,
      deviceMaps: [],
      maps: [ ],
      projects: [],
      blueIcon: null,
      greenIcon: null,
      yellowIcon: null,
      redIcon: null,
      dredIcon: null,
      pColors:{
        0: this.greenIcon,
        1: this.blueIcon,
        2: this.yellowIcon, // 黄色
        3: this.redIcon,
        4: this.dredIcon
      },
      index: 0,
    }
  },
  mounted() {
    this.projects = []
    this.$store.state.user.projects = []
    if(this.$store.state.user.roles.includes("admin")){
      loadProjectList({
        userId: this.$store.state.user.id,
        status: this.$store.state.user.userInfo.status,
        accountType: this.$store.state.user.userInfo.accountType,
        city: this.$store.state.user.userInfo.city,
        county: this.$store.state.user.userInfo.county,
        province: this.$store.state.user.userInfo.province
      }).then(res => {
          this.$store.state.user.projects = [ ...res.data]
          this.projects = [...res.data]
          this.maps =  [...this.projects]
          if( this.maps.length > 0) {
            this.$nextTick(() => {
              this.initMap(0, this.maps[0].provinceName)
            })
          }
  
      }).catch()
    } else {
      loadCustomerProjects({
        userId: this.$store.state.user.id,
        userName: this.$store.state.user.account,
      }).then(res => {
        this.$store.state.user.projects = [ ...res.data]
          this.projects = [...res.data]
          this.maps =  [...this.projects]
          if( this.maps.length > 0) {
            this.$nextTick(() => {
              this.initMap(0, this.maps[0].provinceName)
            })
          }
      }).catch()

    }
    // this.initSize()
  },
  methods: {
    rowDbClickChange(data, device){
      this.$router.push(`/myProject/graph/${data.projectId}/${data.projectName}?lat=${device.latitude}&long=${device.longitude}`)
    },
    rowClassName(row, rowIndex){
      return 'customColor'
    },
    navTodevice(data, device){
      this.$router.push(`/myProject/graph/${data.projectId}/${data.projectName}?lat=${device.latitude}&long=${device.longitude}`)
      // if(device.longitude && device.latitude){
      //   this.deviceMaps[this.index].centerAndZoom( new BMapGL.Point(device.longitude, device.latitude), 20) 
      // } else {
      //   this.$message.warning('无效的地理信息')
      // }
    },
    carouselChange(index){
      this.index = index
      console.log(index)
      this.initMap(index, this.maps[index].provinceName )
    },
    initDevices(index, map){
      // console.log(map, 'map----------------')
      // map.clearOverlays()
      // let pArray = []
      this.maps[index].devices.map((p,i) => {
        if(p.longitude && p.latitude){
          let lng = parseFloat(p.longitude), lat = parseFloat(p.latitude)
          let wgs84Position = transformFromGCJToWGS(lat, lng)
          if(i == Math.floor(this.maps[index].devices.length/2) ){
            map.setView(new L.LatLng(wgs84Position.latitude, wgs84Position.longitude), 13)
          }
          let img = this.pColors[p.dataStatus]
          const myIcon = L.icon({
              iconUrl: img,
              iconSize: [25, 30],
              // iconAnchor: [22, 94],
              iconAnchor: [0, 0],
              popupAnchor: [13, 0],
              // shadowUrl: "my-icon-shadow.png",
              // shadowSize: [68, 95],
              // shadowAnchor: [22, 94],
            });
            const marker = L.marker(new L.LatLng(wgs84Position.latitude, wgs84Position.longitude), {
              icon: myIcon,
              draggable: this.$store.state.user.accountType == 0,
            // draggable: true,
            }).addTo(map);

            marker.on("dragend", (e) => {
                let marker = e.target;
                let position = marker.getLatLng();
              // console.log("新位置：", position, );
              // 把wgs84 转换为火星坐标传给后台
              let resPosition = transformFromWGSToGCJ(position.lat, position.lng)
              movePoint({
                  deviceId: p.id,
                  longitude: resPosition.longitude,
                  latitude: resPosition.latitude
              }).then(res => {
                  if(res.statusCode == '200') {
                  this.$message.success('重新定位成功！')
                  }
              }).catch()
            });


          // let _point = new BMapGL.Point(lng, lat)
          // let bdPoint 
          // new BMapGL.Convertor().translate([_point], 3, 5, (data) => {
          //   bdPoint = data.points[0]
          //   pArray[i] = bdPoint
          //   let marker = new BMapGL.Marker(bdPoint, {
          //     icon: this.pColors[p.dataStatus],
          //     enableDragging: this.$store.state.user.accountType == 0
          //   });
          //   map.addOverlay(marker); // 将标注添加到地图
          //   let dragEndPoint = bdPoint
          //     marker.addEventListener("dragend", () => {
          //         let curPoint = marker.getPosition();
          //         dragEndPoint = curPoint
          //         console.log('拖拽位置', curPoint)
          //         new BMapGL.Convertor().translate([curPoint], 5, 3, (data) => {
          //           movePoint({
          //             deviceId: p.id,
          //             longitude: data.points[0].lng,
          //             latitude: data.points[0].lat
          //           }).then(res => {
          //             if(res.statusCode == '200') {
          //               this.$message.success('重新定位成功！')
          //             }
          //           }).catch()
          //         })
          //     }, { passive: false});

            marker.on("click", (e) => {
              marker.unbindPopup();
              const elements = this.getProjectPopupContent(p);
              marker.bindPopup(elements).openPopup(e.latlng);
            });

              // marker.addEventListener("click", () => {
              //     let curPoint = marker.getPosition();
              //     // console.log('点击事件位置', curPoint)
              //   new BMapGL.Convertor().translate([curPoint], 5, 3, (data) => {
              //     let opts = {
              //         width: 280,
              //         height: 160,
              //         title:  `设备名称：${p.deviceName} `
              //     };
              //     let info = `
              //     IMEI： ${p.imei} <br>
              //     自定义编码： ${p.deviceCode} <br>
              //     电子标签： ${p.rfid} <br>
              //     经度： ${data.points[0].lng} <br>
              //     纬度： ${data.points[0].lat} <br>
              //     安装时间：${p.insTime} <br>`
              //     let infoWindow = new BMapGL.InfoWindow( info, opts);
              //     map.openInfoWindow(infoWindow, dragEndPoint); // 开启信息窗口

              //   })

              // },  { passive: false});

        }
      })

    },
    getProjectPopupContent: (item) => {
      let elements = `<div class="infowindow" style="line-height: 20px;">
          <div style="font-weight: bold; margin-bottom: 4px;"> <span class="title" style="margin-right: 6px">设备名称： </span> <span class="value"> ${item.deviceName} </span> </div>
          <div> <span class="title" style="margin-right: 6px">IMEI： </span> <span class="value"> ${item.imei} </span> </div>
          <div> <span class="title" style="margin-right: 6px">自定义编码： </span> <span class="value"> ${item.deviceCode} </span> </div>
          <div> <span class="title" style="margin-right: 6px">安装时间： </span> <span class="value"> ${item.insTime} </span> </div>
          </div>`
          // <div> <span class="title" style="margin-right: 6px">电子标签： </span> <span class="value"> ${item.rfid} </span> </div>
          // <div> <span class="title" style="margin-right: 6px">经度： </span> <span class="value"> ${item.longitude} </span> </div>
          // <div> <span class="title" style="margin-right: 6px">维度： </span> <span class="value"> ${item.latitude} </span> </div>
          return elements;
    },
    initMap(index, provinceName){
      let height = document.body.clientHeight - 128  
      // this.tableHeight = (height - 140) / 3
      this.tableHeight = height - 240
      this.mapHeight = height - 150
      console.log(height, this.tableHeight, '列表高计算')
      document.getElementById('graph_wrapper').style.width = '96%' 
      document.getElementById('graph_wrapper').style.height = height + 'px'

      const tdtKey = "a60e29bb7b4f94344345b038205fe71f";
      let map = L.map('exampleMap' + index, {
          crs: L.CRS.EPSG4326,
          center: [34.26, 108.96],
          // center: [39.89329, 116.39151],
          zoom: 4,
          maxZoom: 17, //最大缩放层级
          minZoom: 1, //最小缩放层级
          tileSize: 256, //切片大小
          attributionControl: false, // 移除右下角leaflet标识
          zoomControl: false, //禁用 + - 按钮
          // maxBounds: "bounds", //设置边界
          preferCanvas: true, //默认使用svg渲染，设置canvas渲染
          doubleClickZoom: false, //关闭双击缩放
          // dragging: false, //鼠标移动事件
      });
      map.closePopup()
      // 添加缩放结束的事件监听器
      map.on("zoomend", (e) => {
          // console.log("Zoom ended", e);
          // 缩放结束时的逻辑
          var zoomLevel = map.getZoom(); // 获取当前缩放级别
          console.log("Current zoom level:", zoomLevel);
      });
      // 影像图
      const img = L.tileLayer(
          "http://t0.tianditu.gov.cn/img_c/wmts?tk=" +
          tdtKey +
          "&layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
          {
          crossOrigin: "anonymous",
          tileSize: 256,
          zoomOffset: 1,
          noWrap: true,
          }
      );

      // 影像注记
      const cia = L.tileLayer(
          "http://t0.tianditu.gov.cn/cia_c/wmts?tk=" +
          tdtKey +
          "&layer=cia&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
          {
          crossOrigin: "anonymous",
          tileSize: 256,
          zoomOffset: 1,
          noWrap: true,
          }
      );
      // 矢量图
      const vec = L.tileLayer(
          "http://t0.tianditu.gov.cn/vec_c/wmts?tk=" +
          tdtKey +
          "&layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
          {
          crossOrigin: "anonymous",
          tileSize: 256,
          zoomOffset: 1,
          noWrap: true,
          }
      );

      // 矢量注记
      const cva = L.tileLayer(
          "http://t0.tianditu.gov.cn/cva_c/wmts?tk=" +
          tdtKey +
          "&layer=cva&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}",
          {
          crossOrigin: "anonymous",
          tileSize: 256,
          zoomOffset: 1,
          noWrap: true,
          }
      );

      const vector = L.layerGroup([vec, cva]);
      const image = L.layerGroup([img, cia]);

      const baseLayers = {
          矢量: vector,
          影像: image,
      };

      // 初始化显示矢量图层
      // map.addLayer(vector);
      map.addLayer(image);

      // 创建并添加缩放控件
      L.control
          .zoom({
          position: "bottomright", // 可以设置为'topleft', 'topright', 'bottomleft' 或 'bottomright'
          })
          .addTo(map);

      // 创建并添加尺寸控件
      L.control
          .scale({
          position: "bottomleft",
          maxWidth: 200,
          metric: true, // 显示公制尺寸
          imperial: true, // 显示英制尺寸
          })
          .addTo(map);
      // 添加图层控件;
      L.control.layers(baseLayers).addTo(map).setPosition("bottomright");


        this.greenIcon = "/imgs/marker1.png"  
        this.blueIcon = "/imgs/marker2.png"  
        this.yellowIcon = "/imgs/marker3.png"  
        this.redIcon = "/imgs/marker4.png"   
        this.dredIcon = "/imgs/marker5.png"  

        this.pColors ={
          0: this.greenIcon,
          1: this.blueIcon,
          2: this.yellowIcon, // 黄色
          3: this.redIcon,
          4: this.dredIcon
        }
        window.addEventListener("touchmove", () => {}, { passive: false})

        this.deviceMaps[index] = map

        this.initDevices(index, map)

      
    },
    initSize(){
      let height = document.body.clientHeight - 128  
      this.tableHeight = (height - 140) / 3
      console.log(height, this.tableHeight, '列表高计算')
      document.getElementById('graph_wrapper').style.width = '96%' 
      document.getElementById('graph_wrapper').style.height = height + 'px'
      this.initMap()
    },
     
  },
  created(){
    

  }
  
}
</script>

<style lang="scss" >
/**
 table滚动条样式修改 
 */
 
.el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; /* 设置滚动条宽度 */
  height: 6px; /* 设置滚动条高度 */
}
 
.el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 3px; /* 设置滚动条圆角 */
  background: rgba(0, 0, 0, 0.3); /* 设置滚动条颜色 */
}
 
.el-table__body-wrapper::-webkit-scrollbar-track {
  background: #f0f0f0; /* 设置滚动条轨道颜色 */
}
 
.el-table__body-wrapper::-webkit-scrollbar-corner {
  background: #f0f0f0; /* 设置滚动条交叉处颜色 */
}
                        

.hide {
  visibility: hidden;
}
.graph_wrapper {
  margin: 20px auto 0;
  position: relative;
  .projectWraper {
    margin-top: 10px;
    display: flex;
    .infoBox {
      width: 500px;
      margin-right: 30px;
    }
    .projectInfo {
      color:#2185E8;
      text-align: left;
      font-size: 12px;
      line-height: 24px;
      // border: 1px solid #fff;
      margin-bottom: 20px;
      width: 100%;
      .title {
        color:#2185E8;
        font-size: 16px;
      }
      .imgWraper {
        width: 500px;
        overflow: hidden;
        margin-top: 10px;
        border-radius: 5px;
        img {
          width: 100%;
          transition: transform 1s;
          &:hover {
            transform: scale(1.3);
          }
        }
      }
       
     
    }
    .mapWrapper {
      width: 100%;
      border-radius: 8px;
      vertical-align: top;
      display: inline-block;
      touch-action:none;
      // height: calc( 100vh - 580px);
    }
  }
  .deviceTable {
    border-radius: 8px;
    font-size: 16px;
    thead th {
      height: 32px !important;
    }
    thead th .cell{
      font-size: 14px;
    }
    .el-table__body-wrapper tbody {
      tr {
        height: 20px !important;
      }
      
    }
  }
}
.example {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: calc( 100% - 60px);
  background: #0B1120;
  padding: 30px 50px;
  background: url('../../assets/imgs/mapBg.png') no-repeat;
  background-size: 100% 100%;
  .exampleMap {
    width: 100%;
    height: calc( 100% - 70px);
    // height: 100%;
    touch-action:none
  }
  .graph_title {
    color: #fff;
    font-size: 14px;
    background: url('../../assets/imgs/map_title_small.png') no-repeat;
    padding: 5px 20px;
    margin-bottom: 20px;
    &.long {
      background: url('../../assets/imgs/map_title_long.png') no-repeat;
    }
    span {
      cursor: pointer;
    }
  }
}
.el-table tr.customColor:nth-child(2n) .cell.el-tooltip {
  color: #57DEFE;
}
// tr.customColor .td div{
//   color: red !important;
// }
.carousel {
  width: 100%;
  height: 100%;
  // height: 800px;
  // margin: 30px auto;
  .el-carousel__item.is-animating {
    transition: transform 5s ease-in-out, -webkit-transform 5s ease-in-out;
  }
  .el-carousel__container {
    width: 100%;
    height: calc( 100% - 60px);
    .graph_container {
     width: 100%;
     height: 100%;
      background: url('../../assets/imgs/mapBg.png') no-repeat;
      background-size: 100% 100%;
      padding: 30px 50px 10px;
      text-align: center;

    }
    img {
        border-radius: 5px;
      }
  }
  .graph_title {
    color: #fff;
    font-size: 14px;
    background: url('../../assets/imgs/map_title_small.png') no-repeat;
    // background-size: 100% 100%;
    padding: 5px 20px;
    text-align: left;
    &.long {
      background: url('../../assets/imgs/map_title_long.png') no-repeat;
    }

  }

  .total {
    color: #fff;
    margin: 10px 0;
    text-align: left;
  }
  .graph_box {
    // height: calc(100% - 60px);
    height: calc(100% - 30px);
    touch-action:none
    // width: 300px;
    // height: 300px;
  }


}



.documentation-container {
  // margin: 0 20px;
  // padding: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  position: relative;
  // background: #fff;

  .document-btn {
    flex-shrink: 0;
    display: block;
    cursor: pointer;
    background: black;
    color: white;
    height: 60px;
    padding: 0 16px;
    margin: 16px;
    line-height: 60px;
    font-size: 20px;
    text-align: center;
  }
}
</style>
